package com.shengsiyuan.netty.sixthexample.handler;

import com.google.protobuf.MessageLite;
import com.shengsiyuan.netty.sixthexample.proto.MyDataInfo;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class CustomProtobufEncoder extends MessageToByteEncoder<MessageLite> {


    @Override
    protected void encode(ChannelHandlerContext ctx, MessageLite msg, ByteBuf out) throws Exception {

        byte[] body = msg.toByteArray();
        byte[] header = encodeHeader(msg,(short)body.length);
        out.writeBytes(header);
        out.writeBytes(body);
    }

    private byte[] encodeHeader(MessageLite msg, short bodyLength) {
        byte messageType = 0x0f;

        if (msg instanceof MyDataInfo.Person) {
            messageType = 0x00;
        } else if (msg instanceof MyDataInfo.Teacher) {
            messageType = 0x01;
        } else if (msg instanceof MyDataInfo.Student){
            messageType = 0x02;
        }

        byte[] header = new byte[4];
        header[0] = (byte) (bodyLength & 0xff);
        header[1] = (byte) ((bodyLength >> 8) & 0xff);
        header[2] = 0; // 保留字段
        header[3] = messageType;

        return header;

    }
}
